package com.ming.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BIOServer {
    public static void main(String[] args) throws IOException {
        //1.创建一个线程池
        ExecutorService service = Executors.newCachedThreadPool();
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("server running");
        //2.如果有客户端连接 就创建一个线程 与之通信
        while (true) {
            //监听 等待客户端连接
            final Socket socket = serverSocket.accept();
            System.out.println("one client in");
            service.execute(new Runnable() {
                @Override
                public void run() {
                    //可以和客户端通信
                    handler(socket);
                }
            });
        }
    }

    //编写一个handler方法 与客户端通信
    public static void handler(Socket socket) {
        try {
            System.out.println(Thread.currentThread().getName());
            byte[] bytes = new byte[1024];
            //通过socket获得输入流
            InputStream inputStream = socket.getInputStream();
            //循环读取客户端发送的数据
            while (true){
                int read = inputStream.read(bytes);
                if (read != -1){
                    System.out.println(new String(bytes,0,read)); //输出客户端发送的数据
                }else break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
